package me.leiusual.sharing.util.extension

import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.os.AsyncTask
import android.widget.ImageView
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.transition.DrawableCrossFadeFactory
import me.leiusual.sharing.GlideApp
import me.leiusual.sharing.GlideRequest
import me.leiusual.sharing.util.tool.QRCodeUtils
import java.lang.ref.WeakReference

fun ImageView.setQRCode(text: String) {
  QRCodeAsyncTask(WeakReference(this)).execute(text)
}

private class QRCodeAsyncTask(
    private val imageViewRef: WeakReference<ImageView>
) : AsyncTask<String, Void, Bitmap>() {

  override fun doInBackground(vararg params: String?): Bitmap? {
    val text = params.firstOrNull() ?: return null
    return QRCodeUtils.createQRCode(text)
  }

  override fun onPostExecute(result: Bitmap?) {
    val imageView = imageViewRef.get()
    imageView?.setImageBitmap(result)
  }
}

fun ImageView.setImageUrl(url: Any?, block: ((GlideRequest<Drawable>) -> GlideRequest<Drawable>)? = null) {
  GlideApp.with(this)
      .load(url)
      .transition(DrawableTransitionOptions.with(fadeFactory))
      .apply { block?.invoke(this) }
      .into(this)
}

private val fadeFactory = DrawableCrossFadeFactory.Builder()
    .setCrossFadeEnabled(true)
    .build()